package com.example.steveaoblogdemo.controller;

import com.example.steveaoblogdemo.mapper.UserMapper;
import com.example.steveaoblogdemo.utils.RedisUtil;
import com.example.steveaoblogdemo.utils.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Random;

@RestController
@CrossOrigin
public class EmailController {

    @Resource
    private JavaMailSender javaMailSender;


    @Resource
    private RedisUtil redisUtil;

    @Value("${spring.mail.username}") //动态获取配置文件中 发送邮件的账户
    private String sendEmail;

    @GetMapping("/email/getVerifyCode")
    public Result<?> getCode(@RequestParam(defaultValue = "")String email){
        int verifyCode = new Random().nextInt(9999) % (9999 - 1000 + 1) + 1000;
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setFrom(sendEmail);
        simpleMailMessage.setTo(email);
        //邮件标题
        simpleMailMessage.setSubject("SteveAoの博客验证码");
        //邮件内容
        simpleMailMessage.setText("您的验证码是"+verifyCode+" "+"有效期为5分钟"+
                "请注意保存，不要随便告诉他人哦！");
        javaMailSender.send(simpleMailMessage);
        redisUtil.set("verifyCode",verifyCode,300);
        return new Result<>(200,"发送成功",verifyCode);
    }

    @GetMapping("/email/checkVerifyCode")
    public Result<?> checkCode(@RequestParam(defaultValue = "")String code){
       if (code.equals(redisUtil.get("verifyCode").toString())){
           return new Result<>(200,"验证码正确",null);
       }
       return new Result<>(400,"验证码错误",null);
    }

}
